package com.example.jpa.query.controller;

import com.example.jpa.query.entities.User;
import com.example.jpa.query.repository.PagingAndSortingRepositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PagingAndSortingController {

    @Autowired
    private PagingAndSortingRepositories repositories;

    @GetMapping(path = "/page")
    public Page<User> findAllByPage() {
        // 根据每1页10条，并且按照`name` 字段进行倒序排序
        Pageable request = PageRequest.of(1, 10, Sort.by(
                new Sort.Order(Sort.Direction.DESC, "username")));

        return repositories.findAll(request);
    }

    @GetMapping(path = "/sort")
    public Iterable<User> findAllBySort() {
        //根据age进行升序查询。
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.ASC, "age"));
        return repositories.findAll(sort);
    }
}
